<?php

namespace app\api\controller;

use app\admin\model\groupchat\Groupchat;
use app\admin\model\groupchateight\Groupchateight;
use app\admin\model\groupchatfive\Groupchatfive;
use app\admin\model\groupchatfour\Groupchatfour;
use app\admin\model\groupchatnine\Groupchatnine;
use app\admin\model\groupchatseven\Groupchatseven;
use app\admin\model\groupchatsix\Groupchatsix;
use app\admin\model\groupchatten\Groupchatten;
use app\admin\model\groupchatthree\Groupchatthree;
use app\admin\model\groupchattwo\Groupchattwo;
use app\admin\model\groupchatyuangong\Groupchatyuangong;
use app\admin\model\qianghongbao\Qianghongbao;
use app\admin\model\sendhongbao\Sendhongbao;
use app\common\controller\Api;
use think\Db;
use think\Exception;

class Chat extends Api{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function send(){
        $type = $this->request->param('type');
        $content = $this->request->param('content');
        $qun_id = $this->request->param('qun_id');
        if(!$qun_id || $qun_id==''){
            $this->error('缺少群ID');
        }
        $hongbao_id = $this->request->param('hongbao_id');
        $second = $this->request->param('second');
        if(!$qun_id || $qun_id==''){
            $this->error('缺少群ID');
        }

        if($qun_id==1){
            $groupchatModel = new Groupchat();
        }elseif ($qun_id==2){
            $groupchatModel = new Groupchattwo();
        }elseif ($qun_id==3){
            $groupchatModel = new Groupchatthree();
        }elseif ($qun_id==4){
            $groupchatModel = new Groupchatfour();
        }elseif ($qun_id==5){
            $groupchatModel = new Groupchatfive();
        }elseif ($qun_id==6){
            $groupchatModel = new Groupchatsix();
        }elseif ($qun_id==7){
            $groupchatModel = new Groupchatseven();
        }elseif ($qun_id==8){
            $groupchatModel = new Groupchateight();
        }elseif ($qun_id==9){
            $groupchatModel = new Groupchatnine();
        }elseif ($qun_id==10){
            $groupchatModel = new Groupchatten();
        }elseif($qun_id==11){
            $groupchatModel = new Groupchatyuangong();
        }else{
            $this->error('群ID不存在');
        }
        $userinfo = $this->auth->getUserinfo();
        $one = $groupchatModel->where(['user_id'=>$userinfo['id']])->find();
        if($one){
            $one = $one->toArray();
            $avatar = $one['avatar'];
            $nickname = $one['nickname'];
        }else{
            $userModel = new \app\admin\model\User();
            $userinfo = $userModel->where(['id'=>$userinfo['id']])->find()->toArray();
            if($userinfo['avatar']==''){
                $avatar = '/avatar.png';
            }else{
                $avatar = $userinfo['avatar'];
            }
            $nickname = $userinfo['nickname'];
        }

        //查一下发送方是否被禁言
        $qunModel = new \app\admin\model\qun\Qun();
        $quninfo = $qunModel->where(['id'=>$qun_id])->find()->toArray();
        if($quninfo['is_jinyan'] == 1 ){
            $this->error('此群已被全员禁言');
        }
        if($quninfo['jinyanmingdan']!=''){
            $mingdanarr=explode(',',$quninfo['jinyanmingdan']);
            if(in_array($userinfo['id'],$mingdanarr)){
                $this->error('您已被管理员禁言');
            }
        }
        if($type==6 || $type==7){
            if(!$hongbao_id || $hongbao_id==''){
                $this->error('红包ID必传');
            }
        }

        $indata['user_id'] = $userinfo['id'];
        $indata['nickname'] = $nickname;
        $indata['avatar'] = $avatar;
        $indata['content'] = $content;
        $indata['type'] = $type;
        $indata['create_time'] = time();
        if($type==6 || $type==7){
            $indata['hongbao_id'] = $hongbao_id;
        }
        if($type==4){
            $indata['second'] = $second;
        }
        $groupchatModel->insert($indata);
        $this->success('发送成功');
    }

    public function chatrecord(){
        $qun_id = $this->request->param('qun_id');
        if(!$qun_id || $qun_id==''){
            $this->error('缺少群ID');
        }
        $userinfo = $this->auth->getUserinfo();

        if($qun_id==1){
            $groupchatModel = new Groupchat();
        }elseif ($qun_id==2){
            $groupchatModel = new Groupchattwo();
        }elseif ($qun_id==3){
            $groupchatModel = new Groupchatthree();
        }elseif ($qun_id==4){
            $groupchatModel = new Groupchatfour();
        }elseif ($qun_id==5){
            $groupchatModel = new Groupchatfive();
        }elseif ($qun_id==6){
            $groupchatModel = new Groupchatsix();
        }elseif ($qun_id==7){
            $groupchatModel = new Groupchatseven();
        }elseif ($qun_id==8){
            $groupchatModel = new Groupchateight();
        }elseif ($qun_id==9){
            $groupchatModel = new Groupchatnine();
        }elseif ($qun_id==10){
            $groupchatModel = new Groupchatten();
        }elseif($qun_id==11){
            $groupchatModel = new Groupchatyuangong();
        }else{
            $this->error('群ID不存在');
        }

        $qunModel = new \app\admin\model\qun\Qun();
        $quninfo = $qunModel->where(['id'=>$qun_id])->find()->toArray();
        $jinyanarr = explode(",",$quninfo['jinyanmingdan']);
        $guanliarr = explode(",",$quninfo['guanli']);
        $page = $this->request->param('page');
        $pageSize = 20;
        $start=($page-1)*$pageSize;
        $list = collection($groupchatModel->where([])->order('id desc')->limit($start,$pageSize)->select());
        if($list){
            $list = $list->toArray();
            $list = array_reverse($list);
            $newlist = [];
            foreach ($list as $k=>$v){
                $newlist[$k]['id'] = $v['id'];
                $newlist[$k]['nickname'] = $v['nickname'];
                $newlist[$k]['avatar'] = 'http://47.239.156.92'.$v['avatar'];
                if($v['type']==1){
                    $newlist[$k]['content'] = $v['content'];
                }else if($v['type']==2){
                    $newlist[$k]['content'] = $v['content'];
                }else if($v['type']==3){
                    $newlist[$k]['content'] = 'http://47.239.156.92'.$v['content'];
                }else if($v['type']==4){
                    $newlist[$k]['content'] = 'http://47.239.156.92'.$v['content'];
                }else if($v['type']==5){
                    $newlist[$k]['content'] = 'http://47.239.156.92'.$v['content'];
                }else if($v['type']==6){
                    $newlist[$k]['content'] = 'http://47.239.156.92'.$v['content'];
                    $newlist[$k]['hongbao_id'] = $v['hongbao_id'];
                }else if($v['type']==7){
                    $newlist[$k]['content'] = 'http://47.239.156.92'.$v['content'];
                    $newlist[$k]['hongbao_id'] = $v['hongbao_id'];
                }
                $newlist[$k]['user_id'] = $v['user_id'];
                if(in_array($v['user_id'],$jinyanarr)){
                    $newlist[$k]['is_jinyan'] = 1;
                }else{
                    $newlist[$k]['is_jinyan'] = 0;
                }
                if(in_array($v['user_id'],$guanliarr)){
                    $newlist[$k]['is_guanli'] = 1;
                }else{
                    $newlist[$k]['is_guanli'] = 0;
                }
                $newlist[$k]['type'] = $v['type'];
                $newlist[$k]['second'] = $v['second'];
                $newlist[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
                if($v['user_id']==$userinfo['id']){
                    $newlist[$k]['is_me'] = 1;
                }else{
                    $newlist[$k]['is_me'] = 0;
                }
            }
            $this->success('成功',$newlist);
        }else{
            $this->success('成功',[]);
        }
    }

    /**
     * 发红包
     **/
    public function sendhongbao(){
        $type = $this->request->param('type');
        $amount = $this->request->param('amount');
        $nums = $this->request->param('nums');
        if($amount < 1 || $amount > 200){
            $this->error('红包金额只能1到200之间');
        }
        if($nums < 1 || $nums > 100){
            $this->error('红包数量只能1到100之间');
        }
        $qun_id = $this->request->param('qun_id');
        if(!$qun_id || $qun_id==''){
            $this->error('缺少群ID');
        }
        $userinfo =$this->auth->getUserinfo();
        $userModel = new \app\admin\model\User();
        if($type==1){
            if($amount > $userinfo['shouyi_balance']){
                $this->error('余额不足');
            }
        }elseif ($type==2){
            if($amount > $userinfo['hcc_balance']){
                $this->error('余额不足');
            }
        }

        try{
            if($type==1){
                $userModel->where(['id'=>$userinfo['id']])->setDec('shouyi_balance',$amount);
            }elseif ($type==2){
                $userModel->where(['id'=>$userinfo['id']])->setDec('hcc_balance',$amount);
            }
            $sendhongbaoModel = new Sendhongbao();
            $indata['user_id']=$userinfo['id'];
            $indata['qun_id']=$qun_id;
            $indata['amount']=$amount;
            $indata['nums']=$nums;
            $indata['type']=$type;
            $indata['create_time']=time();
            $id = $sendhongbaoModel->insertGetId($indata);
            Db::commit();
            $this->success('发送红包成功',['hongbao_id'=>$id]);
        }catch(Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function qianghongbao(){
        $hongbao_id = $this->request->param('hongbao_id');
        if(!$hongbao_id || $hongbao_id==''){
            $this->error('缺少红包ID');
        }

        $userinfo = $this->auth->getUserinfo();
        $user_id = $userinfo['id'];

        // 获取红包信息
        $sendhongbaoModel = new Sendhongbao();
        $hongbao = $sendhongbaoModel->where(['id'=>$hongbao_id])->find();
        if(!$hongbao){
            $this->error('红包不存在');
        }
        $hongbao = $hongbao->toArray();
        if($hongbao['status'] != 0){
            $this->error('红包已抢完或已过期');
        }

        // 检查是否已经抢过
        $qianghongbaoModel = new Qianghongbao();
        $hasQiang = $qianghongbaoModel->where(['hongbao_id' => $hongbao_id, 'user_id' => $user_id])->find();
        if($hasQiang){
            //$this->error('您已经抢过这个红包了');
            return json_encode([
                'code'=>201,
                'msg'=>'您已经抢过红包了'
            ],JSON_UNESCAPED_UNICODE);
        }
        // 获取已抢人数和金额
        $qiangList = collection($qianghongbaoModel->where(['hongbao_id'=>$hongbao_id])->select());
        if($qiangList){
            $qiangList = $qiangList->toArray();
            $qiangCount = count($qiangList);
            $qiangAmount = array_sum(array_column($qiangList, 'amount'));
        }else{
            $qiangCount = 0;
            $qiangAmount = 0;
        }

        Db::startTrans();
        try {
            // 检查是否抢完
            if($qiangCount >= $hongbao['nums']){
                // 更新红包状态为已抢完
                $sendhongbaoModel->where(['id'=>$hongbao_id])->update(['status' => 1]);
                $this->error('红包已抢完');
            }

            // 计算剩余金额和人数
            $remainingAmount = $hongbao['amount'] - $qiangAmount;
            $remainingNums = $hongbao['nums'] - $qiangCount;

            // 计算抢到的金额
            $qiangAmount = $this->calculateRandomAmount($remainingAmount, $remainingNums);

            // 记录抢红包
            $qiangData = [
                'hongbao_id' => $hongbao_id,
                'user_id' => $user_id,
                'amount' => $qiangAmount,
                'create_time' => time()
            ];
            $qianghongbaoModel->insert($qiangData);

            if($hongbao['type']==1){
                // 更新用户HC余额
                $userModel = new \app\admin\model\User();
                $userModel->where('id', $user_id)->setInc('shouyi_balance', $qiangAmount);
                $userModel->where('id', $user_id)->setInc('hc_hongbao_amount', $qiangAmount);
            }elseif ($hongbao['type']==2){
                // 更新用户HCC余额
                $userModel = new \app\admin\model\User();
                $userModel->where('id', $user_id)->setInc('hcc_balance', $qiangAmount);
                $userModel->where('id', $user_id)->setInc('hcc_hongbao_amount', $qiangAmount);
            }


            //修改红包的己抢金额,数量
            $sendhongbaoModel->where(['id'=>$hongbao_id])->setInc('receive_amount',$qiangAmount);
            $sendhongbaoModel->where(['id'=>$hongbao_id])->setInc('qiang_nums',1);

            // 如果是最后一个人抢，更新红包状态
            if($qiangCount + 1 >= $hongbao['nums']){
                $sendhongbaoModel->where(['id'=>$hongbao_id])->update(['status' => 1]);
            }

            Db::commit();
            $this->success('抢红包成功', [
                'amount' => $qiangAmount,
                'remaining' => $remainingNums - 1
            ]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('抢红包失败：' . $e->getMessage());
        }
    }

    /**
     * 计算随机金额（二倍均值法）
     */
    private function calculateRandomAmount($remainingAmount, $remainingNums) {
        if($remainingNums == 1){
            // 最后一个人，获得剩余所有金额
            return round($remainingAmount, 2);
        }

        // 二倍均值法：在0.01到(剩余金额/剩余人数*2)之间随机
        $max = ($remainingAmount / $remainingNums) * 2;
        $amount = mt_rand(1, $max * 100) / 100;
        $amount = max(0.01, min($amount, $remainingAmount - 0.01 * ($remainingNums - 1)));

        return round($amount, 2);
    }

    public function look(){
        $hongbao_id = $this->request->param('hongbao_id');
        if(!$hongbao_id || $hongbao_id==''){
            $this->error('红包ID必传');
        }
        $userinfo = $this->auth->getUserinfo();
        $qianghongbaoModel = new Qianghongbao();
        $info = $qianghongbaoModel->where(['hongbao_id'=>$hongbao_id,'user_id'=>$userinfo['id']])->find();
        if($info){
            $info = $info->toArray();
            $sendhongbaoModel = new Sendhongbao();
            $sendinfo = $sendhongbaoModel->where(['id'=>$hongbao_id])->find()->toArray();
            $userModel = new \app\admin\model\User();
            $userinfo = $userModel->where(['id'=>$sendinfo['user_id']])->find()->toArray();
            if($userinfo['avatar']==''){
                $avatar = 'http://47.239.156.92/avatar.png';
            }else{
                $avatar = 'http://47.239.156.92'.$userinfo['avatar'];
            }
            $this->success('成功',[
                'amount'=>$info['amount'],
                'create_time'=>date("Y-m-d H:i:s",$info['create_time']),
                'nickname'=>$userinfo['nickname'],
                'avatar'=>$avatar,
                'type'=>$sendinfo['type']]);
        }else{
            $this->success('成功',[]);
        }
    }

    public function chehui(){
        $message_id = $this->request->param('message_id');
        if(!$message_id || $message_id==''){
            $this->error('消息ID必传');
        }
        $qun_id = $this->request->param('qun_id');
        if(!$qun_id || $qun_id==''){
            $this->error('群ID必传');
        }
        if($qun_id==1){
            $groupchatModel = new Groupchat();
        }elseif ($qun_id==2){
            $groupchatModel = new Groupchattwo();
        }elseif ($qun_id==3){
            $groupchatModel = new Groupchatthree();
        }elseif ($qun_id==4){
            $groupchatModel = new Groupchatfour();
        }elseif ($qun_id==5){
            $groupchatModel = new Groupchatfive();
        }elseif ($qun_id==6){
            $groupchatModel = new Groupchatsix();
        }elseif ($qun_id==7){
            $groupchatModel = new Groupchatseven();
        }elseif ($qun_id==8){
            $groupchatModel = new Groupchateight();
        }elseif ($qun_id==9){
            $groupchatModel = new Groupchatnine();
        }elseif ($qun_id==10){
            $groupchatModel = new Groupchatten();
        }elseif ($qun_id==11){
            $groupchatModel = new Groupchatyuangong();
        }else{
            $this->error('群ID不存在');
        }
        $userinfo = $this->auth->getUserinfo();
        $info = $groupchatModel->where(['id'=>$message_id])->find();
        if(!$info){
            $this->error('消息不存在');
        }
        $info = $info->toArray();
        if($info['user_id']!=$userinfo['id']){
            $this->error('您只能撤回自己的消息');
        }
        if(time()-$info['create_time']>30){
            $this->error('消息超过30秒后不能撤回');
        }
        $groupchatModel->where(['id'=>$message_id])->delete();
        $this->success('撤回成功');
    }

    /**禁言**/
    public function jinyan(){
        $user_id = $this->request->param('user_id');
        if(!$user_id || $user_id==''){
            $this->error('用户ID必传');
        }
        $qun_id = $this->request->param('qun_id');
        if(!$qun_id || $qun_id==''){
            $this->error('群ID必传');
        }
        $userinfo = $this->auth->getUserinfo();
        if($user_id == $userinfo['id']){
            $this->error('您不能禁言自已');
        }
        $qunModel = new \app\admin\model\qun\Qun();
        $quninfo = $qunModel->where(['id'=>$qun_id])->find()->toArray();
        if($quninfo['jinyanmingdan']!=''){
            $jinarr=explode(",",$quninfo['jinyanmingdan']);
            if(in_array($user_id,$jinarr)){
                $this->error('对方已经是禁言状态了');
            }
        }
        if($quninfo['guanli']!=''){
            $guanliarr=explode(",",$quninfo['guanli']);
            if(in_array($user_id,$guanliarr)){
                $this->error('对方是管理员，你不能禁言管理员');
            }
        }
        if(!in_array($userinfo['id'],$guanliarr)){
            $this->error('您不是管理员身份不能禁言');
        }
        if($quninfo['jinyanmingdan']!=''){
            $newmingdan = $quninfo['jinyanmingdan'].','.$user_id;
            $qunModel->where(['id'=>$qun_id])->update(['jinyanmingdan'=>$newmingdan]);
        }else{
            $qunModel->where(['id'=>$qun_id])->update(['jinyanmingdan'=>$user_id]);
        }
        $this->success('禁言成功');
    }

    public function huifu(){
        $user_id = $this->request->param('user_id');
        if(!$user_id || $user_id==''){
            $this->error('用户ID必传');
        }
        $qun_id = $this->request->param('qun_id');
        if(!$qun_id || $qun_id==''){
            $this->error('群ID必传');
        }
        $qunModel = new \app\admin\model\qun\Qun();
        $quninfo = $qunModel->where(['id'=>$qun_id])->find()->toArray();
        if($quninfo['jinyanmingdan']!=''){
            $jinarr=explode(",",$quninfo['jinyanmingdan']);
            if(!in_array($user_id,$jinarr)){
                $this->error('对方不是禁言状态');
            }
        }else{
            $this->error('对方不是禁言状态');
        }
        $jinarr=explode(",",$quninfo['jinyanmingdan']);
        $arr = array_diff($jinarr, [$user_id]);
        $str = implode(',', $arr);
        $qunModel->where(['id'=>$qun_id])->update(['jinyanmingdan'=>$str]);
        $this->success('恢得成功');
    }
}
